// client/pages/addLog/addLog.js
import watch from '../../utils/watch.js'
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    watchTotalPrice:true, //如果修改单价或者数量的时候，这里设置为false，watch里面的form.totalPrice就不会触发
    watchItem: false,  //和watchTotalPrice是相对的
    loading:false,
    dateShow: false,
    oilTypeShow: false,
    selectStationName:'',
    form:{
      miles:'',
      createdTime:'',
      oilType:'',
      state:'',
      stationId:'',
      remarks:'',
      price:'',
      quantity:'',
      totalPrice:''
    },
    oilTypeLabel:'',
    minHour: 10,
    maxHour: 20,
    minDate: '',
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    columns: [
      {
        name: '0#柴油',
        code: '0#'
      },
      {
        name: '92#汽油',
        code: '92#'
      },
      {
        name: '95#汽油',
        code: '95#'
      },
      {
        name: '98#汽油',
        code: '98#'
      }
    ]
  },


  addOilLogs: function () {
    let _this = this;
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '正在提交',
    })
    wx.cloud.callFunction({
      name: 'addOilLogs',
      data: this.data.form,
      success: respone => {
        let res = respone.result
        console.log(res)
        if(res.code==200){
          wx.reLaunch({
            url: '/pages/logs/index'
          })
        }else{
          Notify({ type: 'warning', message: res.msg });
        }
        this.setData({
          loading: false
        })
        wx.hideLoading()
      }, fail: err => {
        this.setData({
          loading: false
        })
        wx.showToast({
          title: '数据保存失败，请重试',
          duration: 800,
          icon: 'none'
        })
        console.error("数据保存失败，请重试", err.errMsg)
      }
    })

  },

  setState(event){
    this.setData({
      'form.state': event.target.dataset.state
    })
  },

  onCloseOilType() {
    this.setData({
      oilTypeShow: false
    })

  },
  onCloseTime() {
    this.setData({
      dateShow: false
    })
    console.log(this.data.dateShow)
  },

  setFormDate(event){
    let label = event.target.dataset.input
    this.setData({
     [`form.${label}`]: event.detail
    })
  },

  dateFormat(fmt, date) {
    let ret;
    let opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "M+": (date.getMonth() + 1).toString(),     // 月
      "D+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "m+": date.getMinutes().toString(),         // 分
      "s+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;
  },

  onClickOilType() {
    this.setData({
      oilTypeShow: true,
    })

  },

  onSetOilType(event){
    console.log(event.detail)
    const { picker, value, index } = event.detail;
    console.log(value)
    this.setData({
      'form.oilType': value.code,
      oilTypeLabel: value.name,
      oilTypeShow: false
    })
  },

  onConfirm(event){
    let date = this.dateFormat('YYYY-MM-DD HH:mm', new Date(event.detail))
   
    this.setData({
      'form.createdTime': date,
      'currentDate': event.detail,
      dateShow: false
    });
  },

  onClickDate: function(){
    this.setData({
      'dateShow': true,
      'currentDate': new Date(this.data.form.date).getTime() || new Date().getTime()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    watch.setWatcher(this);
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '需要登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/user/user'
        })
      }, 1000)
    }
  },

  setItemWatch(){
    this.setData({
      watchTotalPrice: false,
      watchItem: true
    })
  },
  setTotalPriceWatch() {
    this.setData({
      watchTotalPrice: true,
      watchItem: false
    })
  },

  // 监听器
  watch: {
    'form.totalPrice': function (newVal, oldVal) {
      if (this.data.watchTotalPrice) {
        let price = Number(this.data.form.price)
        let totalPrice = Number(newVal)
        if (totalPrice == '' || isNaN(totalPrice)) {
          console.log('总价清空了')
          this.setData({
            'form.quantity': ''
          })
        }
        if (price && totalPrice >= price) {
          let quantity = totalPrice / price
          console.log(quantity)
          if (!isNaN(quantity)) {
            setTimeout(() => {
              this.setData({
                'form.quantity': quantity.toFixed(2)
              })
            })
          }

        }

      }
    },
    'form.quantity': function (newVal, oldVal) {
      if (this.data.watchItem) {
        let price = Number(this.data.form.price)
        let quantity = Number(newVal)
        if (quantity == '' || isNaN(quantity)) {
          console.log('加油升数清空了')
          this.setData({
            'form.totalPrice': ''
          })
        }
        if (price && quantity) {
          let totalPrice = price * quantity
          console.log(totalPrice)
          if (!isNaN(totalPrice)) {
            setTimeout(() => {
              this.setData({
                'form.totalPrice': totalPrice.toFixed(2)
              })
            })
          }
        }
      }
    },
    'form.price': function (newVal, oldVal) {
      if (this.data.watchItem) {
        let quantity = Number(this.data.form.quantity)
        let totalPrice = Number(this.data.form.totalPrice)
        let price = Number(newVal)
        if (price == '' || isNaN(price)) {
          console.log('单价清空了')
          this.setData({
            'form.totalPrice': ''
          })
        }
        if (!quantity && totalPrice){ //数量为空 有总价，那么需要计算数量
          //冲突 暂且想想，估计要设3个状态分别对应3个输入框
        }
        if (price && quantity) {
          let totalPrice = price * quantity
          console.log(totalPrice)
          if (!isNaN(totalPrice)) {
            setTimeout(() => {
              this.setData({
                'form.totalPrice': totalPrice.toFixed(2)
              })
            })
          }
        }
      }
    },
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  formReset: function () {
    console.log('form发生了reset事件')
  },
  gotoChooseStation(){
    wx.navigateTo({
      url: '/pages/oilstation/oilstation'
    })
  }
})